package pub.tbc.toolkit.http2.template;

import com.alibaba.fastjson.JSON;
import pub.tbc.toolkit.Loops;
import pub.tbc.toolkit.Objs;
import pub.tbc.toolkit.function.Consumer;
import pub.tbc.toolkit.http2.HttpRequesterImpl;
import pub.tbc.toolkit.http2.ResponseWrapper;

import java.util.Map;

/**
 * @author tbc on 2016/9/18 11:31:22.
 */
public class RestTemplate extends HttpTemplate {

    private static String getUrl(String url, Object... param) {
        if (Objs.isEmpty(param)) return url;
        final StringBuilder pathParam = new StringBuilder();
        Loops.forEach(param, new Consumer<Object>() {
            @Override
            public void accept(Object v) {
                pathParam.append("/").append(v);
            }
        });
        return url + pathParam.toString();
    }

    public static <T> T get(String url, Class<T> c) {
        return get(url, null, c);
    }

    public static <T> T get(String url, Map<String, Object> param, Class<T> c) {
        return get(url, null, param, c);
    }

    public static <T> T get(String url, Map<String, String> headers, Map<String, Object> param, Class<T> c) {
        ResponseWrapper response = new HttpRequesterImpl().get(getUrl(url, param.values()), headers, null);
        if (response.isOk())
            return (T) JSON.parseObject(response.getResult(), c);
        return null;
    }

    public static <T> T delete(String url, Class<T> c) {
        return delete(url, null, c);
    }

    public static <T> T delete(String url, Map<String, Object> param, Class<T> c) {
        return delete(url, null, param, c);
    }

    public static <T> T delete(String url, Map<String, String> headers, Map<String, Object> param, Class<T> c) {
        ResponseWrapper response = new HttpRequesterImpl().delete(getUrl(url, param.values()), headers, null);
        if (response.isOk())
            return (T) JSON.parseObject(response.getResult(), c);
        return null;
    }


}
